package com.snack.shop.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.snack.shop.common.Result;
import com.snack.shop.entity.Address;
import com.snack.shop.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 收货地址控制器
 */
@Tag(name = "收货地址")
@RestController
@RequestMapping("/address")
@RequiredArgsConstructor
public class AddressController {

    private final AddressService addressService;

    @Operation(summary = "获取地址列表")
    @GetMapping("/list")
    public Result<List<Address>> list() {
        Long userId = StpUtil.getLoginIdAsLong();
        List<Address> list = addressService.listByUserId(userId);
        return Result.success(list);
    }

    @Operation(summary = "获取地址详情")
    @GetMapping("/{id}")
    public Result<Address> getDetail(@PathVariable Long id) {
        Address address = addressService.getDetail(id);
        return Result.success(address);
    }

    @Operation(summary = "获取默认地址")
    @GetMapping("/default")
    public Result<Address> getDefault() {
        Long userId = StpUtil.getLoginIdAsLong();
        Address address = addressService.getDefaultAddress(userId);
        return Result.success(address);
    }

    @Operation(summary = "保存地址（新增或编辑）")
    @PostMapping("/save")
    public Result<Void> save(@Validated @RequestBody Address address) {
        Long userId = StpUtil.getLoginIdAsLong();
        address.setUserId(userId);
        
        if (address.getId() == null) {
            addressService.add(address);
        } else {
            addressService.update(address);
        }
        return Result.success();
    }

    @Operation(summary = "删除地址")
    @PostMapping("/delete/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        addressService.delete(id);
        return Result.success();
    }

    @Operation(summary = "设置默认地址")
    @PostMapping("/setDefault/{id}")
    public Result<Void> setDefault(@PathVariable Long id) {
        Long userId = StpUtil.getLoginIdAsLong();
        addressService.setDefault(userId, id);
        return Result.success();
    }
}

